package org.nf.web.view;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.nf.web.servlet.ServletApi;
import org.nf.web.servlet.View;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author czl
 * @Date 2024-05-20
 */
public class ForwardView implements View {

    private final String url;
    /**
     * 缓存请求作用域的数据
     */
    private final Map<String, Object> map = new HashMap<>();

    public ForwardView(String url) {
        this.url = url;
    }

    /**
     * 提供给用胡设置请求作用域参数的方法
     * @param name 键
     * @param object 值
     */
    public void addObject(String name, Object object) {
        map.put(name, object);
    }

    @Override
    public void render(ServletApi api) throws ServletException, IOException {
        HttpServletRequest request = api.request();
        HttpServletResponse response = api.response();
        //将map集合的数据保存到请求作用域
        map.forEach(request::setAttribute);
        //执行转发
        request.getRequestDispatcher(url).forward(request, response);
    }
}